﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using BingleMaps.Models;
using BingleMaps.Services;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace BingleMaps
{
	public partial class UserPinPage : PhoneApplicationPage
	{
		private readonly Binding
			_iconListPickerSelectedItemBinding = new Binding("Icon") { Mode = BindingMode.TwoWay, Converter = (IValueConverter)Application.Current.Resources["PushpinIconConverter"] },
			_colorListPickerSelectedItemBinding = new Binding("Color") { Mode = BindingMode.TwoWay, Converter = (IValueConverter)Application.Current.Resources["PushpinColorConverter"] };
		private UserPin _userPin;

		public UserPinPage()
		{
			InitializeComponent();
			_userPin = (UserPin)DataContext;
			if (_userPin.Image == null) BingMapsServices.GetMapUri(_userPin.Location, result => { if (result != null) _userPin.Image = result.Uri; });
			IconListPicker.SetBinding(ListPicker.SelectedItemProperty, _iconListPickerSelectedItemBinding);
			ColorListPicker.SetBinding(ListPicker.SelectedItemProperty, _colorListPickerSelectedItemBinding);
		}

		protected override void OnBackKeyPress(CancelEventArgs e)
		{
			if (NavigationService != null && NavigationService.CanGoBack)
				base.OnBackKeyPress(e);
			else e.Cancel = true;
		}

		private void PhoneApplicationPageBackKeyPress(object sender, CancelEventArgs e)
		{
			if (SharePanel.Visibility == Visibility.Collapsed) Focus();
			else
			{
				e.Cancel = true;
				SharePanel.Visibility = Visibility.Collapsed;
				ApplicationBar.IsVisible = true;
			}
		}

		private void TitleTextBoxLostFocus(object sender, RoutedEventArgs e)
		{
			((TextBox)sender).SelectionStart = 0;
		}

		private void TextBoxGotFocus(object sender, RoutedEventArgs e)
		{
			((TextBox)sender).SelectAll();
		}

		private void AppBarIconButtonSendClick(object sender, EventArgs e)
		{
			ApplicationBar.IsVisible = false;
			SharePanel.Visibility = Visibility.Visible;
		}

		private void AppBarMenuItemSettingsClick(object sender, EventArgs e)
		{
			NavigationService.Navigate(new Uri("/Views/MoreView.xaml", UriKind.Relative));
		}

		private void SmsHyperlinkButtonClick(object sender, RoutedEventArgs e)
		{
			SharePanel.Visibility = Visibility.Collapsed;
			ApplicationBar.IsVisible = true;
			new SmsComposeTask { Body = _userPin.Title + Environment.NewLine + _userPin.Display }.Show();
		}

		private void EmailHyperlinkButtonClick(object sender, RoutedEventArgs e)
		{
			SharePanel.Visibility = Visibility.Collapsed;
			ApplicationBar.IsVisible = true;
			new EmailComposeTask { Subject = _userPin.Title, Body = _userPin.Display }.Show();
		}
	}
}